package com.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.common.Constants;
import com.example.springboot.common.SnowflakeManager;
import com.example.springboot.controller.DetailDTO;
import com.example.springboot.entity.Detail;
import com.example.springboot.entity.Order;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.DetailMapper;
import com.example.springboot.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class DetailService extends ServiceImpl<DetailMapper, DetailDTO> {
    @Autowired
    private DetailMapper detailMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SnowflakeManager snowflakeManager;
    public DetailDTO create(DetailDTO detailDTO) throws Exception {
//        生成订单编号did
        Long did=snowflakeManager.nextValue();
        detailDTO.setDid(did);
//        为每个商品新建order
        List<Order> orderList=detailDTO.getOrderList();
        java.util.Date day=new Date();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        detailDTO.setTime(sdf.format(day));

        for(Order order:orderList){
            order.setDid(did);
            orderService.create(order);
        }

//        DetailDTO one=getOrderInfo(detailDTO);
//        if(one==null)
//        {
            save(detailDTO);
 //       }
 //       else throw new ServiceException(Constants.CODE_600,"订单已存在");
        return detailDTO;
    }
//    private DetailDTO getOrderInfo(DetailDTO detailDTO){
//        QueryWrapper<DetailDTO> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("did",detailDTO.getDid());
//        DetailDTO one;
//        System.out.println(queryWrapper);
//        try{
//            one=getOne(queryWrapper);
//        }catch (Exception e){
//            throw new ServiceException(Constants.CODE_500,"系统错误");
//        }
//        return one;
//    }
}
